﻿using System;
using System.Linq;
using System.Security;
using Peak.Core.DataInterfaces;
using System.Security.Principal;
using Peak.Core;

namespace Peak.ApplicationServices.Services
{
  public class SprintService : ISprintService
  {
    readonly ISprintRepository _sprintRepository;
    private readonly IPrincipal _principal;

    public SprintService(ISprintRepository sprintRepository, IPrincipal principal)
    {
      _sprintRepository = sprintRepository;
      _principal = principal;
    }

    public Sprint Get(int id)
    {
      Sprint sprint = _sprintRepository.Get(id);
      if(sprint == null || sprint.Project.Users.FirstOrDefault(f=>f.UserName.ToLower()== _principal.Identity.Name.ToLower()) == null)
      {
        throw new EntityNotFoundException();
      }
      return sprint;
    }

    public void Update(Sprint sprint)
    {
      if(sprint == null)
      {
        throw new ArgumentNullException("sprint");
      }
      if (sprint.Project.Users.FirstOrDefault(f => f.UserName.ToLower() == _principal.Identity.Name.ToLower()) == null)
      {
        throw new SecurityException();
      }
      _sprintRepository.SaveOrUpdate(sprint);
    }   

    public void Delete(Sprint sprint)
    {
      if (sprint == null)
      {
        throw new ArgumentNullException("sprint");
      }
      if (sprint.Project.Users.FirstOrDefault(f => f.UserName.ToLower() == _principal.Identity.Name.ToLower()) == null)
      {
        throw new SecurityException();
      }
      _sprintRepository.Delete(sprint);
    }
  }
}
